import { defineStore } from 'pinia';
import { APIBItem } from 'src/types/apib';
import { MatchResult } from 'src/types/matchResult';

const getSessionMatchData = (): MatchResult | undefined => {
  const temp = sessionStorage.getItem('mechanism_matchData')
  if (temp) {
    try {
      const data = JSON.parse(temp)
      return data
    } catch (error) {
      return undefined
    }
  }
  return undefined
}
const getSessionHalfMatchData = (): APIBItem | undefined => {
  const temp = sessionStorage.getItem('half_mechanism_matchData')
  if (temp) {
    try {
      const data = JSON.parse(temp)
      return data
    } catch (error) {
      return undefined
    }
  }
  return undefined
}
export const useMechanismStore = defineStore('mechanism', {
  state: () => ({
    matchData: getSessionMatchData() as MatchResult | undefined,
    halfMatchData: getSessionHalfMatchData() as APIBItem[] | undefined,
    isOldData: false
  }),
  getters: {
    orderId: (state) => state.matchData?.orderId,
  },
  actions: {
    setHalfMatchData(data: APIBItem[]){
      this.halfMatchData = data;
      sessionStorage.setItem('half_mechanism_matchData', JSON.stringify(data));
    },
    resetHalfMatchData(){
      this.halfMatchData = undefined
      sessionStorage.removeItem('half_mechanism_matchData')
    },
    setOldTag(){
      this.isOldData = true
    },
    setMatchData(data: MatchResult) {
      this.matchData = data;
      this.isOldData = false
      sessionStorage.setItem('mechanism_matchData', JSON.stringify(data));
    },
    resetMatchData(){
      this.matchData = undefined
      this.isOldData = false
      sessionStorage.removeItem('mechanism_matchData')
    }
  },
});
